// 封装成类 -> 实例
import { BASE_URL } from './config'
import { LOGIN_TOKEN } from '@/global/contants.js'
import localCache from '@/utils/cache.js'

class Request {
	constructor(baseURL) {
		this.baseURL = baseURL
	}
	request(options) {
		const { url } = options
		options.header = {
			...options.header,
			Authorization: localCache.getCache(LOGIN_TOKEN)
		}
		return new Promise((resolve, reject) => {
			uni.request({
				...options,
				url: this.baseURL + url,
				success: (res) => {
					if (res.data.code === 0) {
						resolve(res.data)
					} else {
						uni.showToast({
							title: res.data.message,
							icon: 'error'
						})
						reject(res.data)
					}
				},
				fail: (err) => {
					console.log('err:', err)
				}
			})
		})
	}
	get(options) {
		return this.request({ ...options, method: 'get' })
	}
	post(options) {
		return this.request({ ...options, method: 'post' })
	}
	put(options) {
			return this.request({ ...options, method: 'put' })
	}
	delete(options) {
			return this.request({ ...options, method: 'delete' })
	}
}

export default new Request(BASE_URL)
